{% extends "base.html" %}

{% block content %}
<style>
/* 液态玻璃效果样式 */
.page-header {
    background: var(--glass-bg);
    backdrop-filter: var(--glass-blur);
    -webkit-backdrop-filter: var(--glass-blur);
    border: 1px solid var(--glass-border);
    border-radius: var(--border-radius);
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: var(--glass-shadow);
    position: relative;
    overflow: hidden;
}

.page-header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
    pointer-events: none;
    z-index: 0;
}

.page-header > div {
    position: relative;
    z-index: 1;
}

.page-title {
    font-size: 2rem;
    font-weight: 700;
    color: #1C1C1E !important;
    margin-bottom: 0.5rem;
    text-shadow: 0 2px 4px rgba(0, 122, 255, 0.1);
}

.page-subtitle {
    color: #6c757d !important;
    margin-bottom: 0;
}

.btn-upload {
    padding: 0.75rem 1.5rem;
    border-radius: 12px;
    font-weight: 600;
    background: rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    box-shadow: 
        0 4px 16px rgba(0, 0, 0, 0.1),
        0 2px 8px rgba(0, 0, 0, 0.05),
        inset 0 1px 0 rgba(255, 255, 255, 0.2) !important;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    color: #1C1C1E !important;
}

.btn-upload::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, transparent 50%);
    pointer-events: none;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.btn-upload:hover {
    transform: translateY(-3px) scale(1.02);
    box-shadow: 
        0 8px 24px rgba(0, 0, 0, 0.15),
        0 4px 12px rgba(0, 0, 0, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.3) !important;
    border-color: rgba(255, 255, 255, 0.3) !important;
    background: rgba(255, 255, 255, 0.15) !important;
    color: #1C1C1E !important;
}

.btn-upload:hover::before {
    opacity: 1;
}

.breadcrumb-nav {
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;
    padding: 1rem 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 
        0 4px 16px rgba(0, 0, 0, 0.05),
        inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.breadcrumb-item {
    color: #1C1C1E !important;
    font-weight: 500;
}

.breadcrumb-item.active {
    color: #007AFF !important;
    font-weight: 600;
}

.file-list {
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(25px);
    -webkit-backdrop-filter: blur(25px);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 
        0 8px 32px rgba(0, 0, 0, 0.08),
        0 2px 8px rgba(0, 0, 0, 0.03),
        inset 0 1px 0 rgba(255, 255, 255, 0.15);
}

.file-item {
    display: flex;
    align-items: center;
    padding: 1rem 1.5rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
}

.file-item:last-child {
    border-bottom: none;
}

.file-item:hover {
    background: rgba(255, 255, 255, 0.1);
    transform: translateX(5px);
}

.file-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.05) 0%, transparent 100%);
    pointer-events: none;
    z-index: 0;
}

.file-item > div {
    position: relative;
    z-index: 1;
}

.file-icon {
    font-size: 1.5rem;
    margin-right: 1rem;
    color: #007AFF;
    width: 30px;
    text-align: center;
}

.folder-icon {
    color: #FF9500;
}

.file-details {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.file-name {
    font-size: 1rem;
    font-weight: 600;
    color: #1C1C1E !important;
    margin-bottom: 0.25rem;
    word-break: break-word;
}

.file-info {
    font-size: 0.85rem;
    color: #6c757d !important;
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
}

.file-info span {
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.file-info i {
    font-size: 0.75rem;
    opacity: 0.7;
}

.file-actions {
    display: flex;
    gap: 0.5rem;
    margin-left: 1rem;
}

.file-actions .btn {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
    border-radius: 8px;
    backdrop-filter: blur(15px);
    -webkit-backdrop-filter: blur(15px);
    border: 1px solid rgba(255, 255, 255, 0.15);
    background: rgba(255, 255, 255, 0.06);
    transition: all 0.3s ease;
}

.file-actions .btn:hover {
    transform: translateY(-2px);
    background: rgba(255, 255, 255, 0.12);
    border-color: rgba(255, 255, 255, 0.25);
}

.file-checkbox {
    margin-right: 1rem;
    display: flex;
    align-items: center;
}

.file-checkbox-input {
    width: 18px;
    height: 18px;
    cursor: pointer;
}

.file-list-header {
    display: flex;
    align-items: center;
    padding: 0.5rem 1rem;
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(15px);
    -webkit-backdrop-filter: blur(15px);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    margin-bottom: 1rem;
}

.form-check-label {
    color: #1C1C1E !important;
    font-weight: 500;
    margin-left: 0.5rem;
    cursor: pointer;
}



/* 暗黑模式适配 */
[data-theme="dark"] .page-header {
    background: rgba(0, 0, 0, 0.3);
    border-color: rgba(255, 255, 255, 0.1);
}

[data-theme="dark"] .page-header::before {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
}

[data-theme="dark"] .page-title {
    color: #ffffff !important;
}

[data-theme="dark"] .page-subtitle {
    color: #bdc3c7 !important;
}

[data-theme="dark"] .btn-upload {
    background: rgba(0, 0, 0, 0.2) !important;
    border-color: rgba(255, 255, 255, 0.15) !important;
    color: #ffffff !important;
}

[data-theme="dark"] .btn-upload:hover {
    background: rgba(0, 0, 0, 0.3) !important;
    border-color: rgba(255, 255, 255, 0.2) !important;
    color: #ffffff !important;
}

[data-theme="dark"] .breadcrumb-nav {
    background: rgba(0, 0, 0, 0.2);
    border-color: rgba(255, 255, 255, 0.1);
}

[data-theme="dark"] .breadcrumb-item {
    color: #ffffff !important;
}

[data-theme="dark"] .file-list {
    background: rgba(0, 0, 0, 0.25);
    border-color: rgba(255, 255, 255, 0.15);
}

[data-theme="dark"] .file-item {
    border-bottom-color: rgba(255, 255, 255, 0.1);
}

[data-theme="dark"] .file-item:hover {
    background: rgba(255, 255, 255, 0.05);
}

[data-theme="dark"] .file-item::before {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.03) 0%, transparent 100%);
}

[data-theme="dark"] .file-name {
    color: #ffffff !important;
}

[data-theme="dark"] .file-info {
    color: #bdc3c7 !important;
}



/* 响应式设计 */
@media (max-width: 768px) {
    .page-header {
        padding: 1.5rem;
    }
    
    .page-title {
        font-size: 1.5rem;
    }
    
    .file-item {
        padding: 0.75rem 1rem;
    }
    
    .file-icon {
        font-size: 1.25rem;
        margin-right: 0.75rem;
        width: 25px;
    }
    
    .file-actions {
        margin-left: 0.75rem;
    }
    
    .file-actions .btn {
        padding: 0.25rem 0.5rem;
        font-size: 0.8rem;
    }
    
    .file-info {
        flex-direction: column;
        gap: 0.25rem;
    }
    
    .file-info span {
        font-size: 0.8rem;
    }
    

}
</style>

<div class="page-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1 class="page-title">
                <i class="fas fa-folder-open me-2"></i>
                文件管理
            </h1>
            <p class="page-subtitle">
                {% if current_user.is_administrator() %}
                    管理所有用户的文件
                    {% if current_user_name != current_user.username %}
                        (当前查看: {{ current_user_name }})
                    {% endif %}
                {% else %}
                    管理您的文件
                {% endif %}
            </p>
        </div>
        <div class="d-flex gap-2">
            {% if current_user.is_administrator() %}
            <select class="form-select" style="max-width: 200px;" onchange="changeUser(this.value)">
                <option value="">选择用户</option>
                {% for user in all_users %}
                <option value="{{ user.id }}" {% if target_user_id|string == user.id|string %}selected{% endif %}>
                    {{ user.username }} {% if user.is_admin %}(管理员){% endif %}
                </option>
                {% endfor %}
            </select>
            {% endif %}
            <button type="button" class="btn btn-primary btn-upload" onclick="document.getElementById('fileInput').click()">
                <i class="fas fa-upload me-2"></i>
                上传文件
            </button>
            <button type="button" class="btn btn-outline-danger" id="batchDeleteBtn" style="display: none;" onclick="batchDeleteFiles()">
                <i class="fas fa-trash me-2"></i>
                批量删除
            </button>
        </div>
        <input type="file" id="fileInput" multiple style="display: none;">
    </div>
</div>

<!-- 面包屑导航 -->
<nav class="breadcrumb-nav">
    <ol class="breadcrumb mb-0">
        <li class="breadcrumb-item">
            <a href="{{ url_for('file_management', user_id=target_user_id) }}" class="text-decoration-none">
                <i class="fas fa-home me-1"></i>根目录
            </a>
        </li>
        {% for part in breadcrumb %}
        <li class="breadcrumb-item {% if loop.last %}active{% endif %}">
            {% if not loop.last %}
            <a href="{{ url_for('file_management', path='/'.join(breadcrumb[:loop.index]), user_id=target_user_id) }}" class="text-decoration-none">
                {{ part }}
            </a>
            {% else %}
            {{ part }}
            {% endif %}
        </li>
        {% endfor %}
    </ol>
</nav>



<!-- 文件列表 -->
{% if files %}
<div class="file-list">
    <div class="file-list-header mb-3">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" id="selectAll" onchange="toggleSelectAll()">
            <label class="form-check-label" for="selectAll">
                全选
            </label>
        </div>
    </div>
    {% for file in files %}
    <div class="file-item" onclick="handleFileClick('{{ file.name }}', {{ 'true' if file.is_dir else 'false' }})">
        <div class="file-checkbox">
            <input type="checkbox" class="form-check-input file-checkbox-input" 
                   value="{{ file.name }}" 
                   data-is-dir="{{ 'true' if file.is_dir else 'false' }}"
                   data-is-registered="{{ 'true' if file.is_registered else 'false' }}"
                   data-has-protected-scripts="{{ 'true' if file.has_protected_scripts else 'false' }}"
                   data-protected-script-name="{{ file.protected_script_name or '' }}"
                   onchange="updateBatchDeleteButton()"
                   onclick="event.stopPropagation();">
        </div>
        <div class="file-icon">
            {% if file.is_dir %}
            <i class="fas fa-folder folder-icon"></i>
            {% else %}
            <i class="fas fa-file-code"></i>
            {% endif %}
        </div>
        <div class="file-details">
            <div class="file-name">{{ file.name }}</div>
            <div class="file-info">
                {% if current_user.is_administrator() %}
                <span><i class="fas fa-user"></i>归属: {{ current_user_name }}</span>
                {% endif %}
                {% if file.is_dir %}
                <span><i class="fas fa-folder"></i>文件夹</span>
                {% else %}
                <span><i class="fas fa-weight-hanging"></i>{{ file.size }}</span>
                {% endif %}
                <span><i class="fas fa-calendar-plus"></i>创建: {{ file.created }}</span>
                <span><i class="fas fa-edit"></i>修改: {{ file.modified }}</span>
            </div>
        </div>
        <div class="file-actions">
            {% if not file.is_dir %}
            <button class="btn btn-outline-primary btn-sm" onclick="event.stopPropagation(); downloadFile('{{ file.name }}')" title="下载">
                <i class="fas fa-download"></i>
            </button>
            {% endif %}
            {% if file.is_registered %}
            <button class="btn btn-outline-warning btn-sm" onclick="event.stopPropagation(); showRegisteredScriptMessage('{{ file.name }}')" title="已注册为脚本，请通过脚本管理删除">
                <i class="fas fa-shield-alt"></i>
            </button>
            {% elif file.has_protected_scripts %}
            <button class="btn btn-outline-warning btn-sm" onclick="event.stopPropagation(); showProtectedFolderMessage('{{ file.name }}', '{{ file.protected_script_name }}')" title="文件夹内包含已注册的脚本，请先删除脚本或移动文件">
                <i class="fas fa-shield-alt"></i>
            </button>
            {% else %}
            <button class="btn btn-outline-danger btn-sm" onclick="event.stopPropagation(); deleteFile('{{ file.name }}')" title="删除">
                <i class="fas fa-trash"></i>
            </button>
            {% endif %}
        </div>
    </div>
    {% endfor %}
</div>
{% else %}
<div class="text-center py-5">
    <div class="upload-icon">
        <i class="fas fa-folder-open"></i>
    </div>
    <h4 class="text-muted">当前目录为空</h4>
    <p class="text-muted">上传一些文件开始使用吧</p>
</div>
{% endif %}

<script>
// 文件上传处理
document.getElementById('fileInput').addEventListener('change', function(e) {
    const files = e.target.files;
    if (files.length > 0) {
        uploadFiles(files);
    }
});



function uploadFiles(files) {
    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i]);
    }
    
    // 添加当前路径
    formData.append('path', '{{ current_path }}');
    
    // 添加用户ID（如果是管理员）
    {% if current_user.is_administrator() and target_user_id %}
        formData.append('user_id', '{{ target_user_id }}');
    {% endif %}
    
    fetch('{{ url_for("upload_files") }}', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin' // 添加凭据，确保会发送Cookie
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('上传失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('上传错误:', error);
        alert('上传失败，请重试');
    });
}

function changeUser(userId) {
    if (userId) {
        window.location.href = '{{ url_for("file_management") }}?user_id=' + userId;
    } else {
        window.location.href = '{{ url_for("file_management") }}';
    }
}

function handleFileClick(fileName, isDir) {
    if (isDir) {
        // 进入文件夹
        const currentPath = '{{ current_path }}';
        let newPath;
        if (currentPath) {
            newPath = currentPath + '/' + fileName;
        } else {
            newPath = fileName;
        }
        window.location.href = '{{ url_for("file_management") }}?path=' + encodeURIComponent(newPath) + '&user_id={{ target_user_id }}';
    } else {
        // 查看文件内容
        const currentPath = '{{ current_path }}';
        let filePath;
        if (currentPath) {
            filePath = currentPath + '/' + fileName;
        } else {
            filePath = fileName;
        }
        window.location.href = '{{ url_for("view_file_page") }}?path=' + encodeURIComponent(filePath) + '&user_id={{ target_user_id }}';
    }
}

function downloadFile(fileName) {
    const currentPath = '{{ current_path }}';
    let filePath;
    if (currentPath) {
        filePath = currentPath + '/' + fileName;
    } else {
        filePath = fileName;
    }
    window.open('{{ url_for("download_file") }}?path=' + encodeURIComponent(filePath) + '&user_id={{ target_user_id }}', '_blank');
}

function deleteFile(fileName) {
    // 获取文件/文件夹的相关信息
    const fileCheckbox = document.querySelector(`input[type="checkbox"][value="${fileName}"]`);
    const isDir = fileCheckbox ? fileCheckbox.getAttribute('data-is-dir') === 'true' : false;
    const isRegistered = fileCheckbox ? fileCheckbox.getAttribute('data-is-registered') === 'true' : false;
    const hasProtectedScripts = fileCheckbox ? fileCheckbox.getAttribute('data-has-protected-scripts') === 'true' : false;
    const protectedScriptName = fileCheckbox ? fileCheckbox.getAttribute('data-protected-script-name') : '';
    
    // 检查是否是已注册的脚本
    if (isRegistered) {
        showRegisteredScriptMessage(fileName);
        return;
    }
    
    // 检查文件夹是否包含已注册的脚本
    if (isDir && hasProtectedScripts) {
        showProtectedFolderMessage(fileName, protectedScriptName);
        return;
    }
    
    // 确认删除
    if (!confirm('确定要删除' + (isDir ? '文件夹' : '文件') + ' "' + fileName + '" 吗？此操作不可恢复！')) {
        return;
    }
    
    const currentPath = '{{ current_path }}';
    let filePath;
    if (currentPath) {
        filePath = currentPath + '/' + fileName;
    } else {
        filePath = fileName;
    }
    
    // 记录删除操作到控制台
    console.log('尝试删除: ' + filePath + (isDir ? ' (文件夹)' : ' (文件)'));
    
    fetch('{{ url_for("delete_file") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'same-origin', // 添加凭据，确保会发送Cookie
        body: JSON.stringify({
            path: filePath,
            user_id: '{{ target_user_id }}'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('删除成功: ' + filePath);
            location.reload();
        } else {
            console.error('删除失败: ' + data.message);
            alert('删除失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('删除错误:', error);
        alert('删除失败，请重试');
    });
}

function showRegisteredScriptMessage(fileName) {
    alert('文件 "' + fileName + '" 已在系统中注册为脚本，请通过脚本管理页面删除。');
}

function showProtectedFolderMessage(folderName, scriptName) {
    alert('安全警告：无法删除受保护的文件夹！\n\n文件夹 "' + folderName + '" 内包含已注册的脚本文件 "' + scriptName + '"。\n\n请先通过以下步骤处理：\n1. 在脚本管理页面删除该脚本\n2. 或将该脚本文件移动到其他文件夹\n\n只有在移除所有已注册脚本后，才能删除此文件夹。');
    
    // 记录到控制台，便于调试
    console.warn('尝试删除受保护文件夹被阻止: ' + folderName + ', 包含脚本: ' + scriptName);
}

// 全选/取消全选
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const fileCheckboxes = document.querySelectorAll('.file-checkbox-input');
    
    fileCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    
    updateBatchDeleteButton();
}

// 更新批量删除按钮显示状态
function updateBatchDeleteButton() {
    const checkedBoxes = document.querySelectorAll('.file-checkbox-input:checked');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    
    if (checkedBoxes.length > 0) {
        batchDeleteBtn.style.display = 'inline-block';
    } else {
        batchDeleteBtn.style.display = 'none';
    }
}

// 批量删除文件
function batchDeleteFiles() {
    const checkedBoxes = document.querySelectorAll('.file-checkbox-input:checked');
    const filesToDelete = [];
    const protectedItems = [];
    
    checkedBoxes.forEach(checkbox => {
        const fileName = checkbox.value;
        const isDir = checkbox.getAttribute('data-is-dir') === 'true';
        const isRegistered = checkbox.getAttribute('data-is-registered') === 'true';
        const hasProtectedScripts = checkbox.getAttribute('data-has-protected-scripts') === 'true';
        const protectedScriptName = checkbox.getAttribute('data-protected-script-name');
        
        if (isRegistered) {
            protectedItems.push(fileName + ' (已注册脚本)');
            console.warn('批量删除中跳过已注册脚本: ' + fileName);
            showRegisteredScriptMessage(fileName);
        } else if (isDir && hasProtectedScripts) {
            protectedItems.push(fileName + ' (包含已注册脚本: ' + protectedScriptName + ')');
            console.warn('批量删除中跳过受保护文件夹: ' + fileName + ', 包含脚本: ' + protectedScriptName);
            showProtectedFolderMessage(fileName, protectedScriptName);
        } else {
            filesToDelete.push({ name: fileName, isDir: isDir });
        }
    });
    
    if (protectedItems.length > 0) {
        alert('安全警告：以下项目无法删除：\n\n' + protectedItems.join('\n') + '\n\n请先通过以下步骤处理：\n1. 在脚本管理页面删除相关脚本\n2. 或将脚本文件移动到其他文件夹\n\n只有在移除所有已注册脚本后，才能删除这些项目。');
        return;
    }
    
    if (filesToDelete.length === 0) {
        alert('没有可删除的文件');
        return;
    }
    
    const fileNames = filesToDelete.map(function(item) { return item.name; }).join('\n');
    if (!confirm('确定要删除以下 ' + filesToDelete.length + ' 个项目吗？\n\n' + fileNames + '\n\n此操作不可恢复！')) {
        return;
    }
    
    // 逐个删除文件
    let deletedCount = 0;
    let failedCount = 0;
    
    filesToDelete.forEach(item => {
        const currentPath = '{{ current_path }}';
        let filePath;
        if (currentPath) {
            filePath = currentPath + '/' + item.name;
        } else {
            filePath = item.name;
        }
        
        fetch('{{ url_for("delete_file") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'same-origin', // 添加凭据，确保会发送Cookie
            body: JSON.stringify({
                path: filePath,
                user_id: '{{ target_user_id }}'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                deletedCount++;
            } else {
                failedCount++;
                console.error('删除失败: ' + item.name + ' - ' + data.message);
            }
        })
        .catch(error => {
            failedCount++;
            console.error('删除错误: ' + item.name + ' - ' + error);
        });
    });
    
    // 等待所有删除操作完成后刷新页面
    setTimeout(() => {
        if (deletedCount > 0) {
            alert('批量删除完成！\n成功删除: ' + deletedCount + ' 个\n失败: ' + failedCount + ' 个');
        }
        location.reload();
    }, 1000);
}
</script>
{% endblock %}